package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.nursing.Util.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author shenhang
 * @date 2025-06-04
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Autowired
    private ElderMapper  elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    /**
     * 申请入住
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        //判断老人是否已经入住
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
          //设置语句where条件
        elderQueryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        elderQueryWrapper.eq(Elder::getStatus, 1);
          //真正开始查询，得到数据存放在elder中
        Elder elder = elderMapper.selectOne(elderQueryWrapper);

        if (ObjectUtils.isNotEmpty(elder)){
            throw new RuntimeException("该老人已经入住");
        }
        //此时老人未入住
        //更新床位状态为已入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //新增或者更新老人数据
        elder= insertOrUpdate(bed, dto.getCheckInElderDto());

        // 生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();

        //新增h合同
        insertContract(dto,elder,contractNo);

        //新增入住信息
       CheckIn checkIn = insertCheckIn1(elder,dto);

        //新增入住配置信息
        insertCheckInConfig(checkIn, elder,dto);
    }




    /**
     * 新增或者更新老人数据
     * @param bed
     * @param checkInElderDto
     */
    private Elder insertOrUpdate(Bed bed, CheckInElderDto checkInElderDto) {
        //准备老人数据
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
            //设置dto中没有设置的三个信息
        elder.setStatus(1);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        //查询老人信息，（通过身份证号，老人的状态不为1）
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        queryWrapper.ne(Elder::getStatus, 1);
        Elder elderDb = elderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(elderDb)){
            elder.setId(elderDb.getId());
            //更新
            elderMapper.updateById(elder);
        }else {
            //新增
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 新增合同
     * @param dto
     * @param elder
     * @param contractNo
     */
    private void insertContract(CheckInApplyDto dto, Elder elder, String contractNo) {
        Contract  contract = new Contract();
        //新增拷贝
        BeanUtils.copyProperties(dto.getCheckInContractDto(),contract);
         //添加合同编号
        contract.setContractNumber(contractNo);
         //设置老人id
//        contract.setElderId(Integer.parseInt(String.valueOf(elder.getId())));
        contract.setElderId(Math.toIntExact(elder.getId()));
//        contract.setElderId(elder.getId());

         //设置老人姓名
        contract.setElderName(elder.getName());
        //状态，开始时间，结束时间


          //得到开始结束时间
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
            //得到状态（做一个判断，入住时间在签约时间之前，合同不生效
            //得到签约时间
            LocalDateTime signDate = dto.getCheckInContractDto().getSignDate();
            Integer status= signDate.isBefore(LocalDateTime.now()) ? 1:0;
            //设置签约状态
            contract.setStatus(status);
          //设置这两个时间
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);

        contractMapper.insert(contract);



    }

    /**
     * 新增入住信息
     * @param elder
     * @param dto
     */
    private CheckIn insertCheckIn1(Elder elder, CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增入住配置信息
     * @param checkIn
     * @param elder
     * @param dto
     */
    private void insertCheckInConfig(CheckIn checkIn, Elder elder, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 申请查看
     * @param id
     * @return
     */















    @Override
    public CheckInDetailVo detail(Long id) {
        //1:创建返回的总vo对象
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        //根据checkinid查询elder的id
        LambdaQueryWrapper<CheckIn> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CheckIn::getId,id);
        CheckIn checkIn = checkInMapper.selectOne(queryWrapper);
        Long elderId = checkIn.getElderId();


        //创建返回的老人vo对象
        CheckInElderVo  checkInElderVo = new CheckInElderVo();
        //2:返回老人信息
        LambdaQueryWrapper<Elder> queryWrapperElder = new LambdaQueryWrapper<>();
        queryWrapperElder.eq(Elder::getId,elderId);
        //得到基本信息数据
        Elder elder = elderMapper.selectOne(queryWrapperElder);
            //属性类型和属性名字保持一致
        BeanUtils.copyProperties(elder,checkInElderVo);
            //老人年龄
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));


        //创建返回的老人家人vo对象
        List<ElderFamilyVo> elderFamilyVo = new ArrayList();
        //3:返回老人家庭信息
//        LambdaQueryWrapper<CheckIn> queryWrapperCheckIn = new LambdaQueryWrapper<>();
//        queryWrapperCheckIn.eq(CheckIn::getElderId,id);
        String remark = checkIn.getRemark();

        //得到家属信息数据
//        List<CheckIn> checkIns = checkInMapper.selectList(queryWrapperCheckIn);
//        checkIns.forEach(checkIn1 -> {
//            String remark = checkIn1.getRemark();
//            ElderFamilyVo elderFamilyVo1 = JSON.parseObject(remark, ElderFamilyVo.class);
//            elderFamilyVo.add(elderFamilyVo1);
//        });
        elderFamilyVo = JSON.parseArray(remark, ElderFamilyVo.class);


        //创建返回的入住配置vo对象
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        //4：返回入住配置信息
        LambdaQueryWrapper<CheckInConfig> queryWrapperCheckInConfig = new LambdaQueryWrapper<>();
        queryWrapperCheckInConfig.eq(CheckInConfig::getCheckInId,id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapperCheckInConfig);

        CheckIn CheckIn = checkInMapper.selectById(id);
        BeanUtils.copyProperties(CheckIn,checkInConfigVo);


        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);

        //5：返回入住信息

        //返回老人签约信息

        //5:创建返回签约的vo对象
        LambdaQueryWrapper<Contract> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Contract::getElderId,elderId);
        Contract contract = contractMapper.selectOne(queryWrapper1);

        //6:返回总信息
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVo);
        checkInDetailVo.setContract(contract);


        return checkInDetailVo;
    }


//    @Override
//    public CheckInDetailVo detail(Long id) {
//
//        // 创建返回的VO对象
//        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
//        // 获取入住配置信息
//        CheckIn checkIn = checkInMapper.selectById(id);
//        LambdaQueryWrapper<CheckInConfig> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(CheckInConfig::getCheckInId, id);
//        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(wrapper);
//
//        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
//        BeanUtils.copyProperties(checkIn,checkInConfigVo);
//        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
//        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
//
//        // 获取老人信息
//        CheckInElderVo checkInElderVo = new CheckInElderVo();
//        // 属性赋值
//        Elder elder = elderMapper.selectById(checkIn.getElderId());
//        BeanUtils.copyProperties(elder,checkInElderVo);
//        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
//        checkInDetailVo.setCheckInElderVo(checkInElderVo);
//        // 设置家属信息
//        String remark = checkIn.getRemark();
//        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
//        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);
//
//        // 合同信息
//        LambdaQueryWrapper<Contract> eldWrapper = new LambdaQueryWrapper<>();
//        eldWrapper.eq(Contract::getElderId,elder.getId());
//        Contract contract = contractMapper.selectOne(eldWrapper);
//        checkInDetailVo.setContract(contract);
//
//        return checkInDetailVo;
//    }

}















